import sys
from PyQt6.QtWidgets import (QApplication, QMainWindow, QPushButton, QWidget, 
                           QVBoxLayout, QHBoxLayout, QTextEdit, QLineEdit, 
                           QScrollArea, QLabel, QFrame, QGraphicsDropShadowEffect)
from PyQt6.QtCore import Qt, QPropertyAnimation, QEasingCurve, QTimer, QThread
from PyQt6.QtGui import QFont, QColor
import aiohttp
import asyncio

api_key="sk-9d17658980ae4a43932027fdb9d147a4"

class FloatingBall(QPushButton):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedSize(60, 60)
        self.setText("AI")
        # 现代化样式
        self.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #667eea, stop:1 #764ba2);
                color: white;
                border-radius: 30px;
                font-weight: bold;
                border: 3px solid white;
                font-size: 16px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #5a6fd8, stop:1 #6a4190);
                border: 3px solid #e3f2fd;
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #4a5fc4, stop:1 #5a3578);
            }
        """)

        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, False)
        self.update_position()
        
    def update_position(self):
        """更新浮动球位置，使其靠右"""
        if self.parent():
            # 获取父窗口尺寸
            parent_width = self.parent().width()
            parent_height = self.parent().height()
            
            x = parent_width - self.width() - 10
            y = int((parent_height - self.height()) // 1.5)
            
            self.move(x, y)
    
    def parent_resize_event(self, event):
        self.update_position()

class ChatBubble(QFrame):
    def __init__(self, message, is_user=True, parent=None):
        super().__init__(parent)
        self.is_user = is_user
        self.setup_ui(message)  
    
    def setup_ui(self, message):
        self.setFrameStyle(QFrame.Shape.NoFrame)
        self.setMaximumWidth(350)
        
        layout = QHBoxLayout()
        layout.setContentsMargins(15, 8, 15, 8)
        
        message_label = QLabel(message)
        message_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse | Qt.TextInteractionFlag.TextSelectableByKeyboard)
        message_label.setWordWrap(True)
        message_label.setStyleSheet(f"""
            QLabel {{
                background: {'qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #667eea, stop:1 #764ba2)' 
                           if self.is_user else '#f8f9fa'};
                color: {'white' if self.is_user else '#2d3748'};
                padding: 12px 16px;
                border-radius: 18px;
                font-size: 14px;
                border: {'none' if self.is_user else '1px solid #e2e8f0'};
                font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            }}
        """)
        
        if self.is_user:
            layout.addStretch()
            layout.addWidget(message_label)
            message_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        else:
            # AI头像
            avatar_label = QLabel("🤖")
            avatar_label.setFixedSize(32, 32)
            avatar_label.setStyleSheet("""
                QLabel {
                    font-size: 16px;
                    background: #667eea;
                    border-radius: 16px;
                    color: white;
                }
            """)
            avatar_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            
            layout.addWidget(avatar_label)
            layout.addWidget(message_label)
            layout.addStretch()
            message_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        
        self.setLayout(layout)

class ChatWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        self.setup_animations()

        manu = open('README.md', 'r',errors="ignore")
        self.manu_content = manu.read()
        sys_prompt = open('.sys_prompt.txt', 'r',errors="ignore")
        self.sys_prompt = sys_prompt.read()

        self.result = ""
        self.all_promopt = [
                 {"role":"system","content":self.sys_prompt},
                 {"role":"system","content":self.manu_content},]
        
        self.close_btn.clicked.connect(self.hide_chat_window)
        self.minimize_btn.clicked.connect(self.hide_chat_window)
        self.send_btn.clicked.connect(self.send_message)
        self.input_field.returnPressed.connect(self.send_message)

        # if history is None:
        #     history = [{"role": "system", "content": "You are a helpful assistant"}]
    def setup_ui(self):
        self.setFixedWidth(420)
        self.setMinimumHeight(500)
        
        self.setStyleSheet("""
            QWidget {
                background: #ffffff;
                border: 1px solid #e2e8f0;
                border-radius: 16px;
            }
        """)
        
        # 添加阴影效果
        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(20)
        shadow.setColor(QColor(0, 0, 0, 60))
        shadow.setOffset(0, 5)
        self.setGraphicsEffect(shadow)
        
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        
        # 标题栏
        self.setup_title_bar(layout)
        
        # 聊天区域
        self.setup_chat_area(layout)
        
        # 输入区域
        self.setup_input_area(layout)
        
        self.setLayout(layout)
    
    def setup_title_bar(self, layout):
        title_bar = QWidget()
        title_bar.setFixedHeight(60)
        title_bar.setStyleSheet("""
            QWidget {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #667eea, stop:1 #764ba2);
                border-top-left-radius: 16px;
                border-top-right-radius: 16px;
                border-bottom: 1px solid rgba(255,255,255,0.1);
                border: none;
            }
        """)
        
        title_layout = QHBoxLayout()
        title_layout.setContentsMargins(20, 0, 10, 0)
        
        # 标题和状态
        title_widget = QWidget()
        title_inner_layout = QVBoxLayout()
        
        title_label = QLabel("AI智能助手")
        title_label.setStyleSheet("""
            QLabel {
                color: white;
                font-weight: bold;
                font-size: 16px;
                font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
                border: none;
            }
        """)
        
        status_label = QLabel("在线 · 随时为您服务")
        status_label.setStyleSheet("""
            QLabel {
                color: rgba(255,255,255,0.8);
                font-size: 12px;
                font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
                border: none;
            }
        """)
        
        title_inner_layout.addWidget(title_label)
        title_inner_layout.addWidget(status_label)
        title_widget.setLayout(title_inner_layout)
        
        title_layout.addWidget(title_widget)
        title_layout.addStretch()
        
        # 控制按钮
        self.minimize_btn = self.create_control_button("−", "#48bb78")
        self.close_btn = self.create_control_button("×", "#f56565")
        
        title_layout.addWidget(self.minimize_btn)
        title_layout.addWidget(self.close_btn)
        
        title_bar.setLayout(title_layout)
        layout.addWidget(title_bar)
    
    def create_control_button(self, text, color):
        btn = QPushButton(text)
        btn.setFixedSize(24, 24)
        btn.setStyleSheet(f"""
            QPushButton {{
                background-color: {color};
                color: white;
                border: none;
                border-radius: 12px;
                font-size: 14px;
                font-weight: bold;
            }}
            QPushButton:hover {{
                background-color: {color};
                opacity: 0.8;
            }}
        """)
        return btn
    
    def setup_chat_area(self, layout):
        self.chat_scroll = QScrollArea()
        self.chat_scroll.setWidgetResizable(True)
        self.chat_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.chat_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
        self.chat_scroll.setStyleSheet("""
            QScrollArea {
                border: none;
                background: transparent;
            }
            QScrollBar:vertical {
                background: rgba(0,0,0,0.1);
                width: 8px;
                border-radius: 4px;
            }
            QScrollBar::handle:vertical {
                background: rgba(102, 126, 234, 0.6);
                border-radius: 4px;
            }
        """)
        
        self.chat_content = QWidget()
        self.chat_layout = QVBoxLayout()
        self.chat_layout.setSpacing(8)
        self.chat_layout.setContentsMargins(16, 16, 16, 16)
        self.chat_layout.addStretch()
        
        self.chat_content.setLayout(self.chat_layout)
        self.chat_scroll.setWidget(self.chat_content)
        
        layout.addWidget(self.chat_scroll, 1)
    
    def setup_input_area(self, layout):
        input_container = QWidget()
        input_container.setStyleSheet("""
            QWidget {
                background: #f8fafc;
                border-top: 1px solid #e2e8f0;
                border-bottom-left-radius: 16px;
                border-bottom-right-radius: 16px;
            }
        """)
        
        input_layout = QHBoxLayout()
        input_layout.setContentsMargins(16, 12, 16, 12)
        input_layout.setSpacing(12)
        
        self.input_field = QLineEdit()
        self.input_field.setPlaceholderText("请输入您的问题...")
        self.input_field.setStyleSheet("""
            QLineEdit {
                background: white;
                border: 2px solid #e2e8f0;
                border-radius: 20px;
                padding: 12px 20px;
                font-size: 14px;
                font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            }
            QLineEdit:focus {
                border-color: #667eea;
            }
        """)
        
        self.send_btn = QPushButton("发送")
        self.send_btn.setFixedSize(80, 44)
        self.send_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #667eea, stop:1 #764ba2);
                color: white;
                border: none;
                border-radius: 22px;
                font-weight: bold;
                font-size: 14px;
                font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #5a6fd8, stop:1 #6a4190);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #4a5fc4, stop:1 #5a3578);
            }
            QPushButton:disabled {
                background: #cbd5e0;
                color: #a0aec0;
            }
        """)
        font = QFont("Microsoft YaHei", 12)
        self.input_field.setFont(font)
        self.input_field.setAttribute(Qt.WidgetAttribute.WA_InputMethodEnabled, True)
        self.input_field.setStyleSheet("""
            QLineEdit {
                background: white;
                border: 2px solid #e2e8f0;
                border-radius: 20px;
                padding: 12px 20px;
                font-size: 14px;
                font-family: 'Microsoft YaHei', 'SimHei', sans-serif;
            }
            QLineEdit:focus {
                border-color: #667eea;
            }
        """)
        input_layout.addWidget(self.input_field, 1)
        input_layout.addWidget(self.send_btn)
        
        input_container.setLayout(input_layout)
        layout.addWidget(input_container)
    
    def setup_animations(self):
        # 显示动画
        self.show_animation = QPropertyAnimation(self, b"geometry")
        self.show_animation.setDuration(400)
        self.show_animation.setEasingCurve(QEasingCurve.Type.OutCubic)
        
        # 隐藏动画
        self.hide_animation = QPropertyAnimation(self, b"geometry")
        self.hide_animation.setDuration(400)
        self.hide_animation.setEasingCurve(QEasingCurve.Type.InCubic)
        
        self.hide_animation.finished.connect(self.hide)
    
    def show_animated(self, parent_geometry):
        self.show()
        start_x = parent_geometry.right()
        end_x = parent_geometry.right() - self.width() - 10
        
        start_rect = self.geometry()
        start_rect.moveRight(start_x)
        
        end_rect = self.geometry()
        end_rect.moveRight(end_x)
        end_rect.setY(20)
        end_rect.setHeight(parent_geometry.height() - 40)
        
        self.setGeometry(end_rect)  # 先设置位置
        self.show_animation.setStartValue(start_rect)
        self.show_animation.setEndValue(end_rect)
        self.show_animation.start()
    
    def hide_animated(self):
        if self.isVisible():
            parent_geometry = self.parent().geometry() if self.parent() else self.geometry()
            start_x = parent_geometry.right() - self.width() - 10
            end_x = parent_geometry.right()
            
            start_rect = self.geometry()
            start_rect.moveRight(start_x)
            
            end_rect = self.geometry()
            end_rect.moveRight(end_x)
            
            self.hide_animation.setStartValue(start_rect)
            self.hide_animation.setEndValue(end_rect)
            self.hide_animation.start()
    
    def add_message(self, message, is_user=True):
        message_widget = ChatBubble(message, is_user)
        self.chat_layout.insertWidget(self.chat_layout.count() - 1, message_widget)
        self.chat_scroll.viewport().update()
        QApplication.processEvents()
        # 滚动到底部
        QTimer.singleShot(50, self.scroll_to_bottom)
    
    def scroll_to_bottom(self):
        scrollbar = self.chat_scroll.verticalScrollBar()
        scrollbar.setValue(scrollbar.maximum())

    def hide_chat_window(self):
        self.all_promopt = [
                 {"role":"system","content":self.sys_prompt},
                 {"role":"system","content":self.manu_content},]
        self.hide_animated()

    def send_message(self):
        message = self.input_field.text().strip()
        self.input_field.clear()
        self.add_message(message=message, is_user=True)
        self.all_promopt.append({"role": "user", "content": message})
        self.thread = QThread()
        self.thread.run = lambda: self._run_async_task(message)
        self.thread.start()
        self.thread.finished.connect(self.on_thread_finished)

    def on_thread_finished(self):
        self.add_message(message=self.result, is_user=False)

    def _run_async_task(self, message: str):
        """在线程中运行异步任务"""
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            self.result_all = loop.run_until_complete(self._call_deepseek_api(message))
            self.all_promopt.append(self.result_all['choices'][0]["message"])
            self.result = self.result_all["choices"][0]["message"]["content"]
        except Exception as e:
            print(e)
        finally:
            loop.close()
    async def _call_deepseek_api(self, prompt: str):
        url = "https://api.deepseek.com/chat/completions"
        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }

        data = {
            "model": "deepseek-chat",
            "messages": self.all_promopt,
            "stream": False
        }
        async with aiohttp.ClientSession() as session:
            async with session.post(url=url,json=data, headers=headers) as response:
                result = await response.json()
                return result

    # def send_message(self):
    #     self.thread = QThread()
        
    #     asyncio.run(self.send_message_async())

    # async def send_message_async(self):
    #     message = self.input_field.text().strip()
    #     self.add_message(message=message, is_user=True)
    #     await asyncio.sleep(0)
    #     result = await self.call_deepseek_api(message)
    #     response_text = result['choices'][0]['message']['content']
    #     self.add_message(message=response_text, is_user=False)

    # async def call_deepseek_api(self, prompt):
    #     url = "https://api.deepseek.com/chat/completions"
    #     headers = {
    #         "Authorization": f"Bearer {api_key}",
    #         "Content-Type": "application/json"
    #     }

    #     data = {
    #         "model": "deepseek-chat",
    #         "messages": [
    #             {"role": "system", "content":
    #              """你仅作为「江苏大学空地协同上位机系统」的专属交互终端，所有回答必须严格限定于该系统的功能、技术细节、操作逻辑或相关领域知识。具体约束如下：
    #              内容范围：仅讨论与该上位机系统直接相关的模块设计（如通信协议、数据解析、UI交互、飞行控制指令转发等）、
    #              硬件对接（如无人机/地面站传感器参数、协同算法接口）、系统部署（如嵌入式环境配置、跨平台兼容性）、测试验证方法（如空地链路稳定性测试、多机协同场景模拟），
    #              或与其研发背景（江苏大学相关课题的技术需求）强关联的内容。
    #              禁止范围：不回答任何与该系统无关的通用技术（如不涉及其他高校类似系统的对比）、非空地协同场景（如纯地面机器人控制）、非上位机相关功能（如无人机端底层飞控代码）、
    #              或超出江苏大学该项目技术范畴的问题（如商业无人机产品说明书）。
    #              回答要求：若问题模糊或可能偏离系统边界，需先澄清“是否属于江苏大学空地协同上位机系统的具体功能/技术环节”，再针对性作答；所有术语需符合该系统研发文档中的定义（如特定通信协议名称、模块缩写含义）。
    #              请始终以该系统的专业技术视角提供精准、聚焦的回应。"""},
    #              {"role":"system","content":self.manu_content},
    #                 {"role": "user", "content": prompt}],
    #         "stream": False
    #     }
    #     async with aiohttp.ClientSession() as session:
    #         async with session.post(url=url,json=data, headers=headers) as response:
    #             result = await response.json()
    #             return result

class ModernMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setup_ui()
        self.setup_connections()
    
    def setup_ui(self):
        self.setWindowTitle("Qt6现代化AI助手示例")
        self.setGeometry(200, 200, 1400, 900)
        
        # 设置主窗口样式
        self.setStyleSheet("""
            QMainWindow {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #f7fafc, stop:1 #edf2f7);
            }
        """)
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 添加一些示例内容
        content_layout = QVBoxLayout()
        title_label = QLabel("欢迎使用Qt6现代化AI助手")
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        title_label.setStyleSheet("""
            QLabel {
                font-size: 32px;
                font-weight: bold;
                color: #2d3748;
                font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
                margin: 100px 0;
            }
        """)
        content_layout.addWidget(title_label)
        
        # 添加操作提示
        tip_label = QLabel("点击右上角的AI按钮开始对话")
        tip_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        tip_label.setStyleSheet("""
            QLabel {
                font-size: 16px;
                color: #4a5568;
                font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
                margin: 20px 0;
            }
        """)
        content_layout.addWidget(tip_label)
        
        central_widget.setLayout(content_layout)
        
        # 创建悬浮球和聊天窗口（作为普通子控件）
        self.floating_ball = FloatingBall(self)
        self.chat_window = ChatWindow(self)
        self.chat_window.hide()
        
        self.update_positions()
    
    def setup_connections(self):
        self.floating_ball.clicked.connect(self.toggle_chat_window)
        self.chat_window.close_btn.clicked.connect(self.hide_chat_window)
        self.chat_window.minimize_btn.clicked.connect(self.hide_chat_window)
        self.chat_window.send_btn.clicked.connect(self.send_message)
        self.chat_window.input_field.returnPressed.connect(self.send_message)
    
    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.update_positions()
    
    def moveEvent(self, event):
        super().moveEvent(event)
        self.update_positions()
    
    def update_positions(self):
        # 更新悬浮球位置（右上角）
        ball_x = self.width() - 80
        ball_y = 60
        self.floating_ball.move(ball_x, ball_y)
        
        # 更新聊天窗口位置
        chat_x = self.width() - self.chat_window.width() - 20
        chat_y = 20
        chat_height = self.height() - 40
        self.chat_window.setGeometry(chat_x, chat_y, self.chat_window.width(), chat_height)
    
    def toggle_chat_window(self):
        if self.chat_window.isVisible():
            self.hide_chat_window()
        else:
            self.show_chat_window()
    
    def show_chat_window(self):
        self.chat_window.show_animated(self.geometry())
        self.chat_window.input_field.setFocus()
    
    def hide_chat_window(self):
        self.chat_window.hide_animated()
    
    def send_message(self):
        message = self.chat_window.input_field.text().strip()
        if message:
            self.chat_window.add_message(message, is_user=True)
            self.chat_window.input_field.clear()
            
            # 模拟AI回复
            self.simulate_ai_response(message)
    
    def simulate_ai_response(self, user_message):
        # 模拟AI处理
        QTimer.singleShot(800, lambda: self.show_ai_response(user_message))
    
    def show_ai_response(self, user_message):
        # 智能回复逻辑
        responses = {
            "你好": "您好！我是基于Qt6的AI助手，很高兴为您服务！",
            "时间": "我无法获取实时时间，但您可以告诉我需要什么时间相关的帮助。",
            "天气": "天气查询功能需要连接网络服务，目前是演示版本。",
            "帮助": "我可以帮您解答问题、提供信息。试试问我一些简单的问题吧！",
            "谢谢": "不客气！有什么其他问题尽管问我。",
        }
        
        # 简单的关键词匹配
        user_msg_lower = user_message.lower()
        response = "我理解您的问题，这是一个基于Qt6的AI助手演示。我可以回答一些简单问题，试试问我'你好'或'帮助'。"
        
        for key, value in responses.items():
            if key in user_msg_lower:
                response = value
                break
        
        self.chat_window.add_message(response, is_user=False)

def main():
    app = QApplication(sys.argv)
    
    # 设置应用程序字体
    font = QFont("Microsoft YaHei", 10)  # 使用更常见的中文字体
    app.setFont(font)
    
    window = ModernMainWindow()
    window.show()
    
    sys.exit(app.exec())

if __name__ == "__main__":
    main()